import { CozeAPI } from '@coze/api';
import Taro from '@tarojs/taro';

const apiClient = new CozeAPI({
  token: 'pat_VMBUv8U0qAvOQ65nAhh4mZQrdMckKG4SF9WA1TA2BVQhVNK19j5tDXkuF97yF0fp',
  baseURL: 'https://api.coze.cn',
  allowPersonalAccessTokenInBrowser: true
});

interface WorkflowResponse {
  status: string;
  output: any;
}

const taroUploadFile = async (filepath: string) => {
  const apiUrl = "https://www.picgo.net/api/1/upload";
  const apiKey = "chv_gMzM_2dbfdbbed22282f043245147e21f0774124d9f0a81c748f4440aaa972c8ff5f00e243245a52fbbf94357d1d33c6f12909ae22daa9e495f0a6f7ad379025c7a20";
  try {
    const response = await Taro.uploadFile({
      url: apiUrl,
      name: "source",
      header: {
        'X-API-Key': apiKey
      },
      filePath: filepath,
      formData: {
        key: apiKey
      }
    });
    console.log("文件上传成功");
    return response.data;
  } catch (error) {
    console.error('文件上传失败:', error);
    Taro.showToast({
      title: '文件上传失败',
      icon: 'error'
    });
  }
};

const callDeleteImageUrl = (deleteUrl: string) => {
  Taro.request({
    url: deleteUrl,
    method: 'DELETE',
    header: {
      'Content-Type': 'application/json',
      'Authorization': 'Bearer pat_n1KzPDgOIvKRmB83pnIO7OnYf48HmQAGMrygPTdZPnbb8aHVJo0oSUqiWudsf3HF'
    }
  }).then((res)=>{
    console.log("图片分析过程出错，调用删除图片");
    console.log(res);
  });

}

const handleImageUpload = async (filePath: string): Promise<WorkflowResponse> => {
  try {

    // const originImg: File = file.originalFileObj;
    // const filePath = file.path;
    console.log("filePath: " + filePath);
    Taro.showLoading({
      title: '文件上传中...'
    })
    const imageInfo:any = await taroUploadFile(filePath);
    Taro.hideLoading();
    const imageJSON = JSON.parse(imageInfo);
    console.log(imageJSON);
    console.log(imageJSON?.image);
    
    const deleteUrl = imageJSON?.image?.delete_url;
    const imageUrl = imageJSON?.image?.medium?.url;
    if (!imageUrl) {
      console.log('图片上传失败');
      Taro.showToast({
        title: '图片上传失败',
        icon: 'error',
        duration: 3000,
      });
      return {
        status: 'fail',
        output: 'fail'
      };
    }

    Taro.showLoading({
      title: '正在分析食谱'
    })

    const res = await Taro.request({
      url: 'https://api.coze.cn/v1/workflow/run',
      method: 'POST',
      header: {
        'Content-Type': 'application/json',
        'Authorization': 'Bearer pat_n1KzPDgOIvKRmB83pnIO7OnYf48HmQAGMrygPTdZPnbb8aHVJo0oSUqiWudsf3HF'
      },
      data: {
        workflow_id: '7463757703438385162',
        parameters: {
          input: imageUrl
        }
      },
      fail: (err) => {
        console.log(err);
        Taro.showToast({
          title: '图片分析失败',
          icon: 'error',
          duration: 3000,
        });
        callDeleteImageUrl(deleteUrl);
        return {
          status: 'fail',
          output: 'fail'
        };
      },
    });
    Taro.hideLoading();

    return {
      status: 'success',
      output: res.data
    };
  } catch (error) {
    console.error('Error uploading image:', error);
    throw error;
  }
};
export { handleImageUpload };
